#define OS_PORT_VERSION 320					//Version number of the uCOS-II LINUX port

#define SHOWTID 1

/*
*********************************************************************************************************
   Includes
*********************************************************************************************************
*/

#include    <stdio.h>
#include    <stdlib.h>
#include    <stdarg.h>
#include    <sys/time.h>
#include    <sys/sem.h>
#include    <pthread.h>
#include    <linux/unistd.h>
#include    <asm/unistd.h>
#include    <string.h>
#include    "os_cpu.h"
#include    "os_cfg.h"
#include    "ucos_ii.h"

typedef struct itimerval ITIMERVAL;
#define NINTERRUPTS 8
void (*interruptTable[NINTERRUPTS])();
union semun
{
    int val;
    struct semid_ds *buf;
    unsigned short *array;
};
void OS_CRITICAL_INIT()
{
    sem=semget(1,1,0666|IPC_CREAT);
    union semun sem_union;
    sem_union.val=255;
    semctl(sem, 0, SETVAL, sem_union);
}
void OS_ENTER_CRITICAL()
{
    struct sembuf sem_b;
    sem_b.sem_num=0;
    sem_b.sem_flg=0;
    sem_b.sem_op=-1;
    if(semop(sem,&sem_b,1)==-1)
    {
        fprintf(stderr,"sem p failed");
    }
    //printf("-1\n");
}
void OS_EXIT_CRITICAL()
{
    struct sembuf sem_b;
    sem_b.sem_num=0;
    sem_b.sem_flg=0;
    sem_b.sem_op=1;
    if(semop(sem,&sem_b,1)==-1)
    {
        fprintf(stderr,"sem v failed");
    }
    //printf("+1\n");
}
void OSCtxSw(void)
{
    printf("%d\n",OSTCBHighRdy->OSTCBPrio);
    OS_TCB* th=OSTCBHighRdy;
    OS_TCB* tp=OSTCBCur;
    OSTCBCur=OSTCBHighRdy;
    OSPrioCur=OSPrioHighRdy;
    //if(th->OSTCBPrio<OS_TASK_TMR_PRIO)
    pthread_kill(*th->threadcb,SIGQUIT);
    //if(tp->OSTCBPrio<OS_TASK_TMR_PRIO)
    pthread_kill(*tp->threadcb,SIGINT);

    //printf("h2\n");

}
void OSIntCtxSw(void)
{}
void OSStartHighRdy(void)
{
    OSRunning=TRUE;
    pthread_kill(*(OSTCBHighRdy->threadcb),SIGQUIT);
    while(1);
}
INT16U OSPortVersion(void)
{}
void OSTickISR(int arg)
{
        OSIntEnter();
        OSTimeTick();
        OSIntExit();
}
void OSTimeTickInit()
{
    ualarm(1000000/OS_TICKS_PER_SEC, 1000000/OS_TICKS_PER_SEC);

    timer.sa_handler=OSTickISR;
    timer.sa_flags=0;
    sigemptyset(&timer.sa_mask);;
    sigaction(SIGALRM, &timer, 0);
}
OS_STK *OSTaskStkInit(void (*task) (void *pd), void *pdata, OS_STK *ptos, INT16U opt)
{   OS_STK *stk;

    stk = (OS_STK *) ptos;                                      // Load stack pointer
    *--stk = (INT32U) pdata;					// Push pdata on the stack
    *--stk = (INT32U) task;					// Push the task start address on the stack

    return stk;
}
void OSInitHookBegin()
{
}
void OSTCBInitHook(OS_TCB * pTcb)
{
}
void OSInitHookEnd()
{
}


void OSTaskCreateHook(OS_TCB *pTcb)
{
}


void OSTaskDelHook(OS_TCB * pTcb)
{
}


void OSTaskIdleHook()
{
}


void OSTaskStatHook()
{
}


void OSTimeTickHook()
{
}


void OSTaskSwHook()
{
}





